package club.web51.classroom_tool.Controllers;

import club.web51.classroom_tool.DO.collDO.Academy;
import club.web51.classroom_tool.DO.collDO.Major;
import club.web51.classroom_tool.DO.sysDO.Msg;
import club.web51.classroom_tool.Enums.MsgEnum;
import club.web51.classroom_tool.Exceptions.ErrDataException;
import club.web51.classroom_tool.Services.MajorService;
import club.web51.classroom_tool.Utils.MsgUtil;
import club.web51.classroom_tool.Utils.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 服务类
 * @author Hanyuhao
 * @since 1.0.0
 */
@RestController
@CrossOrigin
@RequestMapping("/major")
@Api(value = "专业模块",tags={"专业操作接口"})

public class MajorController {

    final
    MajorService majorService;

    public MajorController(MajorService majorService) {
        this.majorService = majorService;
    }

    /**
     * 根据Major的字段,自动生成条件,字段的值为null不生成条件
     * http://localhost:8080/user/?id=1
     * @param major 实体对象
     * @param pageable 分页/排序对象
     * @return 返回的是实体,里面涵盖分页信息及状态码
     */
     @GetMapping
     @ApiOperation("动态查询，可输入对应对象的一个或多个属性")
     @RequiresPermissions(logical = Logical.OR, value = {"1","2", "3"})
     ResponseEntity<Object> search(Major major, Pageable pageable) {
             return majorService.search(major, pageable);
     }
    @PostMapping
    Msg create(@RequestBody @Valid Major major, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new ErrDataException(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        major.setId(null);
        majorService.updateOne(major);
        return MsgUtil.success();
    }
    @PutMapping
    @ApiOperation("修改专业")
    @RequiresPermissions(logical = Logical.AND, value = { "3"})
    Msg update(@Valid Major major,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new ErrDataException(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        if(ObjectUtil.isNull(major.getId()))
            throw new ErrDataException(MsgEnum.ERROR_DATA_EMPTY);
        majorService.updateOne(major);
        return MsgUtil.success();
    }
    @DeleteMapping("/")
    @ApiOperation("删除专业，输入ID")
    @RequiresPermissions(logical = Logical.AND, value = {"3"})
    Msg delete(Long id){
        majorService.deleteOne(id);
        return MsgUtil.success();
    }
}
